import {
    createBrowserRouter,
    RouterProvider,
    Navigate,
    Outlet,
    useLocation,
    useNavigate,
} from 'react-router-dom';
import React , { useEffect } from 'react';
import baseRoutes from './routeConfig';
import { RouteConfig } from './types';
import MainLayout from '../layouts/MainLayout';
import { useAuth } from '../hooks/useAuth';
import Exceptions from '../pages/Exception/404';
import Login from '../pages/Login';

// -------------------------- 路由守卫 --------------------------
/** 登录守卫：未登录拦截 */
const AuthGuard: React.FC<{ children: React.ReactNode }> = ({ children }) => {
    const { isLogin } = useAuth();
    const location = useLocation();
    const navigate = useNavigate();

    useEffect(() => {
        // 未登录 → 跳登录页，记录回跳路径
        if (!isLogin) {
            navigate('/login', { state: { from: location.pathname } });
        }
    }, [isLogin, location, navigate]);

    return isLogin ? <>{children}</> : null;
};

/** 全局守卫：处理404、路由日志等 */
const GlobalGuard: React.FC<{ children: React.ReactNode }> = ({ children }) => {
    const location = useLocation();
    const navigate = useNavigate();

    useEffect(() => {
        // 路由切换日志
        console.log(`[路由守卫] 访问路径：${location.pathname}`);

        // 检查当前路径是否存在于路由配置中（避免手动输入无效路径）
        const isPathValid = (path: string, routes: RouteConfig[]): boolean => {
            for (const route of routes) {
                if (route.path === path || (route.items && isPathValid(path, route.items))) {
                    return true;
                }
            }
            return false;
        };

        // 无效路径 → 跳404
        if (
            location.pathname !== '/login' &&
            location.pathname !== '/404' &&
            !isPathValid(location.pathname, baseRoutes)
        ) {
            navigate('/404', { replace: true });
        }
    }, [location.pathname, navigate]);

    return <>{children}</>;
};

// -------------------------- 路由生成 --------------------------
/** 从路由配置生成React Router可用的路由 */
const generateRoutes = (routes:any): any[] => {
    return routes.flatMap((route: RouteConfig) => {
        // 跳过隐藏路由和登录页（单独处理）
        if (route.hidden || route.path === '/login') return [];

        // 嵌套路由（如会员模块）
        if (route.items && route.items.length > 0) {
            return [
                {
                    path: route.path,
                    element: <Outlet />,
                    children: [
                        // 嵌套路由默认跳第一个子路由
                        { index: true, element: <Navigate to={route.items[0].path} replace /> },
                        ...generateRoutes(route.items),
                    ],
                },
            ];
        }

        // 普通路由
        return {
            path: route.path,
            element: route.component ? React.createElement(route.component) : <Navigate to="/404" replace />,
        };
    });
};

// -------------------------- 路由实例 --------------------------
const router = createBrowserRouter([
    {
        path: '/login',
        element: <Login />,
        // element: <baseRoutes.find((r) => r.path === '/login')?.component || <Navigate to="/404" />},
    },
    {
        path: '/',
            element: (
        <AuthGuard>
            <GlobalGuard>
                <MainLayout />
            </GlobalGuard>
        </AuthGuard>
    ),
        children: [
        // 根路径默认跳可视化大屏
        { index: true, element: <Navigate to="/largeSize" replace /> },
        // 业务路由
        ...generateRoutes(baseRoutes),
        // 404页面
        { path: '404', element: <Exceptions /> },
    ],
    },
    // 所有未匹配路由跳404
    { path: '*', element: <Navigate to="/404" replace /> },
]);

// 路由提供者
const AppRouter = () => {
    return <RouterProvider router={router} />;
};

export default AppRouter;
